package com.nanrui.mutualinductor.ui.page;

import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.widget.Toast;

import com.batman.baselibrary.base.BaseLocationActivity;
import com.nanrui.mutualinductor.AidlPacket;
import com.nanrui.mutualinductor.AidlPacketCallback;
import com.nanrui.mutualinductor.BluetoothCallback;
import com.nanrui.mutualinductor.BluetoothInfo;
import com.nanrui.mutualinductor.IBluetooth;
import com.nanrui.mutualinductor.communicate.PacketCallback;
import com.nanrui.mutualinductor.data.DKPacket;
import com.nanrui.mutualinductor.data.Packet_13;
import com.nanrui.mutualinductor.service.DKService;
import com.network.utils.LogUtils;

import java.util.Timer;


public abstract class DKActivity extends BaseLocationActivity implements BluetoothCallback, AidlPacketCallback {

    public static final int REQ_CODE_ADD_CT = 300;
    public static final int REQ_CODE_ADD_METER = 100;
    public static final int REQ_CODE_ADD_PT = 200;
    public static final String RESP_CT_INFO = "CTInfo";
    public static final String RESP_METER_INFO = "MeterInfo";
    public static final String RESP_PT_INFO = "PTInfo";
    private IBluetooth bluetooth;
    private long deviceTime;
    private ServiceConnection serviceConnection;
    private long time;
    private Timer timer;

    @Override
    public IBinder asBinder() {
        return null;
    }


    /**
     * BluetoothCallback回调
     */

    @Override
    public void onBondStateChanged(BluetoothDevice paramBluetoothDevice, int paramInt1, int paramInt2)
            throws RemoteException {
    }

    @Override
    public void onConnectError(BluetoothInfo paramBluetoothInfo) {
    }

    @Override
    public void onConnected(BluetoothInfo paramBluetoothInfo)
            throws RemoteException {
    }

    @Override
    public void onDisconnected(BluetoothInfo paramBluetoothInfo)
            throws RemoteException {
//        if ((this instanceof MainActivity)) {
//            Toast.makeText(this, "������������������", 0).show();
//        } else {
//            paramBluetoothInfo = new Intent();
//            paramBluetoothInfo.setClass(this, MainActivity.class);
//            paramBluetoothInfo.setFlags(335544320);
//            startActivity(paramBluetoothInfo);
//        }
    }

    @Override
    public void onDiscoveryFinished()
            throws RemoteException {
    }

    @Override
    public void onDiscoveryStarted()
            throws RemoteException {
    }

    @Override
    public void onFound(BluetoothDevice paramBluetoothDevice)
            throws RemoteException {
    }


    @Override
    public void onPreConnect(BluetoothInfo paramBluetoothInfo)
            throws RemoteException {
    }

    @Override
    public void onPreDisconnect(BluetoothInfo paramBluetoothInfo)
            throws RemoteException {
    }

    @Override
    public void onStateChanged(int paramInt1, int paramInt2)
            throws RemoteException {
    }


    @Override
    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
//        StringBuilder localStringBuilder = new StringBuilder();
//        localStringBuilder.append(getClass().getName());
//        localStringBuilder.append(".onCreate...");
//        paramBundle.info(localStringBuilder.toString());
//        getWindow().addFlags(128);
//        paramBundle = getActionBar();
//        if (paramBundle != null) {
//            paramBundle.setHomeButtonEnabled("android.intent.action.MAIN".equals(getIntent().getAction()) ^ true);
//            paramBundle.setIcon(17170445);
//            paramBundle.setDisplayHomeAsUpEnabled("android.intent.action.MAIN".equals(getIntent().getAction()) ^ true);
//            paramBundle.setElevation(0.0F);
//        }
    }


    @Override
    protected void onStart() {
        super.onStart();
//        Logger localLogger = LOG;
//        StringBuilder localStringBuilder = new StringBuilder();
//        localStringBuilder.append(getClass().getName());
//        localStringBuilder.append(".onStart...");
//        localLogger.info(localStringBuilder.toString());
        this.serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName paramAnonymousComponentName, IBinder paramAnonymousIBinder) {
                bluetooth = IBluetooth.Stub.asInterface(paramAnonymousIBinder);
                try {
                    if (bluetooth != null) {
                        serviceConnected();
                        bluetooth.registerCallback(DKActivity.this);
                    }
                    serialPortConnected();
                } catch (RemoteException exception) {
                    exception.printStackTrace();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName paramAnonymousComponentName) {
            }
        };
        bindService(new Intent(this, DKService.class), this.serviceConnection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 服务起来了
     */
    protected void serviceConnected() {

    }


    @Override
    protected void onResume() {
        super.onResume();
//        Logger localLogger = LOG;
//        StringBuilder localStringBuilder = new StringBuilder();
//        localStringBuilder.append(getClass().getName());
//        localStringBuilder.append(".onResume...");
//        localLogger.info(localStringBuilder.toString());

    }

    @Override
    protected void onPause() {
        super.onPause();
//        Logger localLogger = LOG;
//        StringBuilder localStringBuilder = new StringBuilder();
//        localStringBuilder.append(getClass().getName());
//        localStringBuilder.append(".onPause...");
//        localLogger.info(localStringBuilder.toString());
    }


    @Override
    protected void onStop() {
        if (this.timer != null) {
            this.timer.cancel();
            this.timer.purge();
        }
//        Logger localLogger = LOG;
//        StringBuilder localStringBuilder = new StringBuilder();
//        localStringBuilder.append(getClass().getName());
//        localStringBuilder.append(".onStop...");
//        localLogger.info(localStringBuilder.toString());
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        unbindService(this.serviceConnection);
//        Logger localLogger = LOG;
//        StringBuilder localStringBuilder = new StringBuilder();
//        localStringBuilder.append(getClass().getName());
//        localStringBuilder.append(".onDestroy...");
//        localLogger.info(localStringBuilder.toString());
        super.onDestroy();
    }


    public void onUpdateDateTime() {
        Packet_13 localPacket_13 = new Packet_13();
        localPacket_13.setCount(3);
        localPacket_13.setmType((short) 0);
        localPacket_13.setmDateTime(System.currentTimeMillis() / 1000L + 28800L);
        sendPacket(localPacket_13, new PacketCallback() {
            @Override
            public void packetReceived(DKPacket dkPacket) {

                Packet_13 paramAnonymousPacket_13 = (Packet_13) dkPacket;
                if ((paramAnonymousPacket_13 != null) && (((Packet_13) paramAnonymousPacket_13).getsStatus() == 255)) {
//                    DKActivity.access$302(DKActivity.this, (paramAnonymousPacket_13.getsDataTime() - 28800L) * 1000L);
//                    DKActivity.access$102(DKActivity.this, System.currentTimeMillis());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            ((TextView) findViewById(2131296390)).setText(new SimpleDateFormat("yyyy���MM���dd��� HH:mm:ss", Locale.getDefault()).format(new Date(deviceTime)));
                            Toast.makeText(DKActivity.this, "校准时间成功", Toast.LENGTH_LONG).show();
                        }
                    });
                    return;
                }
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(DKActivity.this, "校准时间失败", Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }


    protected void serialPortConnected() {
//        this.timer = new Timer();
//        this.time = 0L;
//        this.timer.schedule(new TimerTask() {
//            public void run() {
//                if (getBluetoothInfo().getConnectStatus() != 2) {
//                    return;
//                }
//                if (System.currentTimeMillis() - time > 60000L) {
//                    sendPacket(new Packet_14(), new PacketCallback() {
//                        @Override
//                        public void packetReceived(DKPacket dkPacket) {
//
//                            Packet_14 paramAnonymous2Packet_14 = (Packet_14) dkPacket;
////                            DKActivity.access$102(DKActivity.this, System.currentTimeMillis());
////                            final Object localObject = paramAnonymous2Packet_14.getMessageCode();
//                            if (paramAnonymous2Packet_14 != null) {
////                                Logger localLogger = DKActivity.LOG;
////                                paramAnonymous2Packet_14 = new StringBuilder();
////                                paramAnonymous2Packet_14.append("������������. ���������: ");
////                                paramAnonymous2Packet_14.append(((DKMessageCode) localObject).getCode());
////                                localLogger.error(paramAnonymous2Packet_14.toString());
//                                return;
//                            }
////                            localObject = findViewById(2131296390);
////                            if (localObject != null) {
////                                DKActivity.access$302(DKActivity.this, (paramAnonymous2Packet_14.getsTime() - 28800L) * 1000L);
//                                runOnUiThread(new Runnable() {
//                                    public void run() {
//                                        TextView localTextView = (TextView) findViewById(2131296297);
//                                        StringBuilder localStringBuilder = new StringBuilder();
//                                        localStringBuilder.append((int) paramAnonymous2Packet_14.getsBatt());
//                                        localStringBuilder.append("%");
//                                        localTextView.setText(localStringBuilder.toString());
//                                        ((TextView) localObject).setText(new SimpleDateFormat("yyyy���MM���dd��� HH:mm:ss", Locale.getDefault()).format(new Date(deviceTime)));
//                                        localTextView = (TextView) findViewById(2131296656);
//                                        localStringBuilder = new StringBuilder();
//                                        localStringBuilder.append(paramAnonymous2Packet_14.getsTP());
//                                        localStringBuilder.append("��� ");
//                                        localStringBuilder.append(paramAnonymous2Packet_14.getsRH());
//                                        localStringBuilder.append("%RH");
//                                        localTextView.setText(localStringBuilder.toString());
//                                    }
//                                });
//                                if (Math.abs(time - deviceTime) > 120000L) {
//                                    if (timeCheckDialog == null) {
//                                        DKActivity.access$402(DKActivity.this, new TimeCheckDialogFragment());
//                                    }
//                                    if ((timeCheckDialog.getDialog() == null) || (!timeCheckDialog.getDialog().isShowing())) {
//                                        paramAnonymous2Packet_14 = new Bundle();
//                                        paramAnonymous2Packet_14.putLong("hostTime", time);
//                                        paramAnonymous2Packet_14.putLong("guestTime", deviceTime);
//                                        timeCheckDialog.setArguments(paramAnonymous2Packet_14);
//                                        timeCheckDialog.show(getFragmentManager(), null);
//                                    }
////                                }
//                            }
//                        }
//                    });
//                } else {
//                    final View localView = findViewById(2131296390);
//                    if (localView != null) {
//                        DKActivity.access$302(DKActivity.this, deviceTime + 1000L);
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                ((TextView) localView).setText(new SimpleDateFormat("yyyy���MM���dd��� HH:mm:ss", Locale.getDefault()).format(new Date(deviceTime)));
//                            }
//                        });
//                    }
//                }
//            }
//        }, 0L, 1000L);
    }


    /**
     * 蓝牙相关操作
     */

    public void cancelBluetoothDiscovery() {
        try {
            this.bluetooth.cancelDiscovery();
        } catch (RemoteException localRemoteException) {
            LogUtils.e(TAG, "AIDL连接异常", localRemoteException.getCause());
        }
    }

    public void connectBluetooth(BluetoothDevice paramBluetoothDevice) {
        try {
            this.bluetooth.connect(paramBluetoothDevice);
        } catch (RemoteException localRemoteException) {
            LogUtils.e(TAG, "AIDL连接异常", localRemoteException.getCause());
        }
    }

    public void disconnectBluetooth() {
        try {
            this.bluetooth.disconnect();
        } catch (RemoteException localRemoteException) {
            LogUtils.e(TAG, "AIDL连接异常", localRemoteException.getCause());
        }
    }

    public BluetoothInfo getBluetoothInfo() {
        try {
            BluetoothInfo localBluetoothInfo = this.bluetooth.getBluetoothInfo();
            return localBluetoothInfo;
        } catch (RemoteException localRemoteException) {
            LogUtils.e(TAG, "AIDL连接异常", localRemoteException.getCause());
        }
        return null;
    }

    public boolean isBluetoothEnable() {
        try {
            boolean bool = this.bluetooth.isEnable();
            return bool;
        } catch (RemoteException localRemoteException) {
            LogUtils.e(TAG, "AIDL连接异常", localRemoteException.getCause());
        }
        return false;
    }

    public void startBluetoothDiscovery() {
        try {
            this.bluetooth.startDiscovery();
        } catch (RemoteException localRemoteException) {
            LogUtils.e(TAG, "AIDL连接异常", localRemoteException.getCause());
        }
    }

    public <T extends DKPacket> void sendPacket(DKPacket paramDKPacket, PacketCallback<T> paramPacketCallback) {
        try {
            IBluetooth localIBluetooth = this.bluetooth;
            AidlPacket localAidlPacket = new AidlPacket(paramDKPacket, paramPacketCallback);
            localIBluetooth.sendPacket(localAidlPacket);
        } catch (RemoteException exception) {

            LogUtils.e(TAG, "AIDL连接异常", exception.getCause());
        }
    }

    public void switchBluetooth() {
        try {
            this.bluetooth.switchBluetooth();
        } catch (RemoteException localRemoteException) {
            LogUtils.e(TAG, "AIDL连接异常", localRemoteException.getCause());
        }
    }
}
